package com.keti.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.keti.Dao.ApplyReceiveDao;
import com.keti.Dao.RecordDao;
import com.keti.Dao.stuffDao;
import com.keti.DaoImpl.ApplyReceiveDaoImpl;
import com.keti.DaoImpl.RecordDaoImpl;
import com.keti.DaoImpl.suffDaoImpl;
import com.keti.pojo.ApplyReceive;
import com.keti.pojo.record;
import com.keti.pojo.stuff;

/**
 * Servlet implementation class CheckApplyServlet
 */
@WebServlet("/CheckApplyServlet")
public class CheckApplyServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		int id = Integer.parseInt(request.getParameter("id"));
		ApplyReceiveDao ard = new ApplyReceiveDaoImpl();
		ApplyReceive ar = new ApplyReceive();
		ar = ard.queryOne(id);
		RecordDao rd = new RecordDaoImpl();
		record r = new record();
		r.setUid(ar.getUid());
		r.setUname(ar.getUname());
		r.setSid(ar.getSid());
		r.setSname(ar.getSname());
		stuffDao sd = new suffDaoImpl();
		stuff s = new stuff();
		s = sd.queryOne(ar.getSid());
		System.out.println(s.getCount2());
		System.out.println(ar.getCount());
		if(s.getCount2()>=ar.getCount()){
			r.setScount2(ar.getCount());
			String FORMAT = "yyyy-MM-dd HH:mm:ss"; 
			SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
			String time = sdf.format(new Date());
			r.setTime(time);
			rd.add(r);
			s.setCount2(s.getCount2()-ar.getCount());
			if(s.getCount2()==0) {
				s.setStatus("已领完");
			}
			sd.updata(s);
			ar.setStatus("审核通过");
			ard.updata(ar);
			response.sendRedirect("ShowApplyReceiveServlet");
		}else if(s.getCount2()<ar.getCount()){
			response.sendRedirect("");
			//返回申请失败页面
		}
		
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
